package com.box.ai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.box.ai.common.tools.MinioUtil;
import com.box.ai.mapper.PDFUploadMapper;
import com.box.ai.pojo.entity.PdfChat;
import com.box.ai.service.PDFUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;

@Service
public class PDFUploadServiceImpl extends ServiceImpl<PDFUploadMapper, PdfChat> implements PDFUploadService {

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.objectName}")
    private String objectName;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private PDFUploadMapper pdfUploadMapper;


    @SneakyThrows
    @Override
    public Boolean upload(MultipartFile file, String chatId) {
        //将文件上传到minion
        minioUtil.createBucket(bucket);
        if (objectName != null) {
            minioUtil.uploadBucket(file.getInputStream(), bucket, objectName + "/" + file.getOriginalFilename());
        } else {
            minioUtil.uploadBucket(file.getInputStream(), bucket, file.getOriginalFilename());
        }

        //文件持久化到数据库
        PdfChat pdfChat = new PdfChat();
        pdfChat.setChatId(chatId);
        pdfChat.setType("pdf");
        PdfChat pdfChat1 = pdfUploadMapper.selectByChatId(chatId);
        if (Objects.nonNull(pdfChat1)){
            return true;
        }
        pdfChat.setFileName(file.getOriginalFilename());
        int insert = pdfUploadMapper.insert(pdfChat);
        return insert>0;
    }



    @Override
    public String getFileName(String chatId) {
        PdfChat pdfChat = pdfUploadMapper.selectByChatId(chatId);
        return pdfChat.getFileName();
    }

    @SneakyThrows
    @Override
    public Resource getFile(String chatId) {
        PdfChat pdfChat = pdfUploadMapper.selectByChatId(chatId);
        InputStream inputStream = minioUtil.downLoad(bucket, objectName + "/" + pdfChat.getFileName());
        return new InputStreamResource(inputStream);
    }

}
